import time
from datetime import datetime

import pytz

from model.base import Session
from model.entities import File

"""
把 datetime 类型的 create_time、update_time 同步到 timestamp 类型的 create_stamp、update_stamp
"""


def sync_time():
    db = Session()
    # 查询数据总量，走索引加速
    total = db.query(File).filter(File.id > 0).count()
    start = 0
    time_0 = time.time()
    # 每次同步 100 条记录
    while start * 100 < total:
        idx_from = start * 100
        idx_to = (start + 1) * 100
        start_time = time.time()
        files = db.query(File).filter(File.id >= idx_from, File.id < idx_to)
        end_time = time.time()
        print(f"同步成功 ===> from {idx_from} to {idx_to}, 用时 : {end_time - start_time} s")
        for file in files:
            file.create_stamp = datetime.fromtimestamp(file.create_time.timestamp()).isoformat(' ', 'seconds')
            file.update_stamp = datetime.fromtimestamp(file.update_time.timestamp()).isoformat(' ', 'seconds')
        db.commit()
        start += 1

    db.commit()
    time_1 = time.time()
    print(f"总共 {total} 条记录， 已同步完成, 用时 : {time_1 - time_0} s")
    db.close()


def stamp_to_int(stamp) -> int:
    """
    将 TIMESTAMP 对象转化为 int
    :param stamp:
    :return:
    """

    # 将时间对象转换为时间元组（time.struct_time 对象）。时间元组是一个包含了年、月、日、小时、分钟、秒等时间信息的对象
    timetuple = stamp.timetuple()
    # 将 TIMESTAMP 转换为时间戳
    float_stamp = time.mktime(timetuple)
    return int(float_stamp)

def switch_timezone(stamp):
    # 接收 UTC 时间
    utc_time = stamp
    # 获取当前系统时间
    now = datetime.now()
    # 获取当前系统时区
    local_timezone = now.astimezone().tzinfo
    local_time = utc_time.replace(tzinfo=pytz.utc).astimezone(local_timezone)
    return local_time

def trans_time(stamp):
    """
    将 utc 时间转换成当前时区的时间戳，并返回时间戳整数值
    :param stamp:
    :return:
    """
    return stamp_to_int(switch_timezone(stamp))



